package com.train.common.intercepter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.train.common.domin.Member;
import com.train.common.until.MemberLoginContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.jiawa.train.common.util.JwtUtil;

/**
 * 添加一个拦截器用来获取登录的用户信息，至于使不使用这个拦截器看每个模块的需求
 * 要使用的模块实现WebMvcConfigurer接口，将这个组件添加进去即可
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)){
            JSONObject jsonObject = JwtUtil.getJSONObject(token);
            System.out.println("当前登录会员：{}"+jsonObject);
            LOG.info("当前登录会员：{}", jsonObject);
            Member member = JSONUtil.toBean(jsonObject, Member.class);
            System.out.println("当前登录会员转换后"+member.getId());
            MemberLoginContextUtil.setMember(member);
        }
        return true;
    }
}
